package com.ccsoft.thread.service;

/**
 * 2021年12月17日 13:42:21 chanchaw
 * 3个线程分别只输出a,b,c。要求交替输出结果如下：
 * abcabcabcabcabc
 */
public class No12Supersede {

    public static void main(String[] args) {
        Supersede supersede = new Supersede(1,5);
        new Thread(() -> {
            supersede.print("a",1,2);
        },"t1").start();

        new Thread(() -> {
            supersede.print("b",2,3);
        },"t2").start();

        new Thread(() -> {
            supersede.print("c",3,1);
        },"t3").start();
    }
}

class Supersede {
    private int flag;
    private int loopNumber;

    public Supersede(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }

    public void print(String printContent, int flag, int nextFlag){
        for (int i = 0; i < this.loopNumber; i++) {
            synchronized (this){
                while( this.flag != flag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print(printContent);
                this.flag = nextFlag;
                this.notifyAll();
            }
        }

    }
}
